package com.example.app;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.app.Websocket.APP;
import com.example.app.Websocket.DataWebSocketManager;
import com.example.app.sharescreen.ShareScreen;
import com.example.app.ui.Message.ChatMessage;
import com.example.app.ui.Message.MessageAdapter;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
public class ChatpageActivity extends AppCompatActivity  implements DataWebSocketManager.DataMessageListener {
    private static final int PICK_IMAGE_REQUEST = 1001;
    private String  targetUserId;
    private DataWebSocketManager dataWebSocketManager;
    private RecyclerView recyclerView;
    private MessageAdapter messageAdapter;
    private List<ChatMessage> messageList;
    private View overlay;
    String username;
    private LinearLayout bottomSheetMenu;
    private int menuHeight;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.chatpage);
        EditText messageInput = findViewById(R.id.messageInput);
        SharedPreferences sharedPreferences = getSharedPreferences("user_credentials", Context.MODE_PRIVATE);
        username = sharedPreferences.getString("username", "");
        Button sendButton = findViewById(R.id.sendButton);
        recyclerView = findViewById(R.id.recyclerView_messages);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        messageList = new ArrayList<>();
        messageList.add(new ChatMessage(ChatMessage.TYPE_RECEIVED,ChatMessage.CONTENT_TEXT,"我们可以开始聊天了","系统"));
        APP.initializeDataWebSocket(getApplicationContext(),username);
        dataWebSocketManager= APP.getDataWebSocketManager();
        dataWebSocketManager.setMessageListener(this); // 添加此行设置监听器
        messageAdapter = new MessageAdapter(this, messageList, targetUserId);
        recyclerView.setAdapter(messageAdapter);
        targetUserId = sharedPreferences.getString("CurrentUserid", "");
        sendButton.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("ObsoleteSdkInt")
            @Override
            public void onClick(View view) {
                String message = messageInput.getText().toString();
                System.out.println("发送的数据为:"+message);
                messageInput.setText("");
                if (!message.isEmpty() && dataWebSocketManager != null ) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        messageList.add(new ChatMessage(
                                ChatMessage.TYPE_SENT,
                                ChatMessage.CONTENT_TEXT,  // 修改这里
                                message,
                                username
                        ));
                        recyclerView.setAdapter(messageAdapter);
                        dataWebSocketManager.sendTextMessage(username,targetUserId,message);
                        recyclerView.postDelayed(() -> {
                            if (!messageList.isEmpty()) {
                                recyclerView.smoothScrollToPosition(messageList.size() - 1);
                            }
                        }, 100);
                    }
                    messageInput.setText("");
                }else {
                    System.out.println("dataWebSocketManager为空");
                }
            }
        });
        overlay = findViewById(R.id.overlay);
        bottomSheetMenu = findViewById(R.id.bottom_sheet_menu);
        ImageButton btnAdd = findViewById(R.id.btn_add);
        bottomSheetMenu.post(() -> {
            menuHeight = bottomSheetMenu.getHeight();
            bottomSheetMenu.setTranslationY(menuHeight);
        });
        setupMenuOptions();
        btnAdd.setOnClickListener(v -> toggleBottomSheetMenu());
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        closeWebSocket();
    }
    private void closeWebSocket() {
    }
    private void toggleBottomSheetMenu() {
        if (bottomSheetMenu.getVisibility() == View.VISIBLE) {
            hideBottomSheetMenu();
        } else {
            showBottomSheetMenu();
        }
    }
    private void showBottomSheetMenu() {
        overlay.setVisibility(View.VISIBLE);
        bottomSheetMenu.setVisibility(View.VISIBLE);
        bottomSheetMenu.animate().translationY(0).setDuration(300).start();
    }
    private void hideBottomSheetMenu() {
        overlay.setVisibility(View.GONE);
        bottomSheetMenu.animate().translationY(menuHeight).setDuration(300).withEndAction(() -> bottomSheetMenu.setVisibility(View.GONE)).start();
    }
    private void setupMenuOptions() {
        int[] optionIds = {
                R.id.option_video_call,
                R.id.option_voice_call,
                R.id.option_gallery,
                R.id.option_camera,
                R.id.option_screen_share,
                R.id.option_video_conference
        };
        for (int id : optionIds) {
            findViewById(id).setOnClickListener(v -> {
                handleMenuClick(v.getId());
                hideBottomSheetMenu();
            });
        }
    }
    private void handleMenuClick(int viewId) {
        if (viewId == R.id.option_video_call) {
            Log.d("VideoCall", "Initiating video call to: " + targetUserId);
            Intent intent = new Intent(ChatpageActivity.this, VideoChatActivity.class);
            intent.putExtra("TARGET_USER_ID", targetUserId);
            startActivity(intent);
        } else if (viewId == R.id.option_voice_call) {
            System.out.println("语音通话请求发起成功");
            Log.d("ChatMenu", "语音通话请求已发送");
        } else if (viewId == R.id.option_gallery) {
            Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(intent, PICK_IMAGE_REQUEST);
            Log.d("ChatMenu", "打开相册选择媒体文件");
        } else if (viewId == R.id.option_camera) {
            Log.d("ChatMenu", "启动相机拍照");
        } else if (viewId == R.id.option_screen_share) {
            Log.d("ChatMenu", "开始屏幕共享");
            Intent intent = new Intent(ChatpageActivity.this, ShareScreen.class);
            intent.putExtra("TARGET_USER_ID", targetUserId);
            startActivity(intent);
        } else if (viewId == R.id.option_video_conference) {
            Log.d("ChatMenu", "发起视频会议");
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null) {
            Uri imageUri = data.getData();
            try {
                File imageFile = saveImageToCache(imageUri);
                messageList.add(new ChatMessage(
                        ChatMessage.TYPE_SENT,
                        ChatMessage.CONTENT_IMAGE,
                        imageFile.getAbsolutePath(),
                        username
                ));
                InputStream is = getContentResolver().openInputStream(imageUri);
                ByteArrayOutputStream buffer = new ByteArrayOutputStream();
                byte[] chunk = new byte[4096];
                int bytesRead;
                while ((bytesRead = is.read(chunk)) > 0) {
                    buffer.write(chunk, 0, bytesRead);
                }
                byte[] imageData = buffer.toByteArray();
                JSONObject metadata = new JSONObject();
                metadata.put("from", username);
                metadata.put("to", targetUserId);
                metadata.put("type", "image");
                String metaString = metadata.toString();
                byte[] metaBytes = metaString.getBytes(StandardCharsets.UTF_8);
                int metaLength = metaBytes.length;
                ByteArrayOutputStream combinedStream = new ByteArrayOutputStream();
                DataOutputStream dataStream = new DataOutputStream(combinedStream);
                dataStream.writeInt(metaLength);
                dataStream.write(metaBytes);
                dataStream.write(imageData);
                dataStream.flush();
                dataWebSocketManager.sendBinaryMessage(combinedStream.toByteArray());
                messageAdapter.notifyItemInserted(messageList.size() - 1);
            } catch (Exception e) {
                Toast.makeText(this, "发送失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }
    }@Override
    public void onTextMessageReceived(String fromUser, String message) {
        runOnUiThread(() -> {
            messageList.add(new ChatMessage(ChatMessage.TYPE_RECEIVED,ChatMessage.CONTENT_TEXT,message,fromUser));
            messageAdapter.notifyItemInserted(messageList.size() - 1);
            recyclerView.smoothScrollToPosition(messageList.size() - 1);
        });
    }
    @Override
    public void onImageMessageReceived(String fromUser, String imageUrl) {
        runOnUiThread(() -> {
            System.out.println(fromUser + " 发送了一张图片: " + imageUrl);
        });
    }
    @Override
    public void onAudioMessageReceived(String fromUser, String audioUrl) {
        System.out.println("-----------------------------------onAudioMessageReceived----------------------------------------------");
    }
    @Override
    public void onFileMessageReceived(String fromUser, String fileUrl) {
        System.out.println("-------------------------------------onFileMessageReceived--------------------------------------------");
    }
    @Override
    public void onConnectionStatusChanged(boolean isConnected) {
        System.out.println("-------------------------------------------onConnectionStatusChanged--------------------------------------");
    }
    @Override
    public void onImageReceived(String fromUser, byte[] imageData) {
        runOnUiThread(() -> {
            try {
                // 保存接收的图片
                File imageFile = saveReceivedImage(imageData);

                // 添加消息
                messageList.add(new ChatMessage(
                        ChatMessage.TYPE_RECEIVED,
                        ChatMessage.CONTENT_IMAGE,
                        imageFile.getAbsolutePath(),
                        fromUser
                ));
                messageAdapter.notifyItemInserted(messageList.size() - 1);
                recyclerView.smoothScrollToPosition(messageList.size() - 1);
            } catch (IOException e) {
                Toast.makeText(this, "图片保存失败", Toast.LENGTH_SHORT).show();
            }
        });
    }
    private void saveImage(byte[] imageData) {
        try {
            File storageDir = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "ChatImages");
            if (!storageDir.exists()) {
                storageDir.mkdirs();
            }
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
            String fileName = "IMG_" + timeStamp + ".png";
            File imageFile = new File(storageDir, fileName);
            try (FileOutputStream fos = new FileOutputStream(imageFile)) {
                fos.write(imageData);
                fos.flush();
                runOnUiThread(() -> Toast.makeText(this,
                        "图片已保存至: " + imageFile.getAbsolutePath(),
                        Toast.LENGTH_LONG).show());
            }
        } catch (IOException e) {
            runOnUiThread(() -> Toast.makeText(this,
                    "保存失败: " + e.getMessage(),
                    Toast.LENGTH_SHORT).show());
        }
    }
    private File saveImageToCache(Uri uri) throws IOException {
        InputStream inputStream = getContentResolver().openInputStream(uri);
        File cacheDir = new File(getCacheDir(), "temp_images");
        if (!cacheDir.exists()) cacheDir.mkdirs();
        File outputFile = new File(cacheDir, System.currentTimeMillis() + ".jpg");

        try (FileOutputStream outputStream = new FileOutputStream(outputFile)) {
            byte[] buffer = new byte[4 * 1024];
            int read;
            while ((read = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, read);
            }
            outputStream.flush();
        }
        return outputFile;
    }
    private File saveReceivedImage(byte[] data) throws IOException {
        File storageDir = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "received_images");
        if (!storageDir.exists()) storageDir.mkdirs();

        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
        File imageFile = new File(storageDir, "IMG_" + timeStamp + ".jpg");

        try (FileOutputStream fos = new FileOutputStream(imageFile)) {
            fos.write(data);
        }
        return imageFile;
    }
}